<template>
  <a-modal :visible="showModal" @cancel="close()" fullscreen>
    <template #title> {{ modal.name }}流程发起 </template>
    <div class="flow-main">
      <a-tabs
        class="tabs-wrap"
        :activeKey="activeKey"
        @change="tabChange"
        style="padding-bottom: 16px"
        size="large"
        type="capsule"
      >
        <a-tab-pane key="1" title="表单信息">
          <iframe
            v-if="iframeSrc"
            ref="iframeRef"
            :src="iframeSrc"
            allowfullscreen="true"
            webkitallowfullscreen="true"
            mozallowfullscreen="true"
            frameborder="0"
            width="100%"
            :height="iframeHeight"
            scrolling="no"
          ></iframe>
        </a-tab-pane>
        <a-tab-pane key="2" title="流程图">
          <template v-if="activeKey == '2'">
            <Flow ref="flowBox"></Flow>
          </template>
        </a-tab-pane>
      </a-tabs>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="close()">
          <template #icon>
            <icon-undo />
          </template>
          返 回
        </a-button>
        <template v-if="activeKey == '1'">
          <a-button v-if="buttonAuth.save">保 存</a-button>
          <a-button type="primary" @click="submit" v-if="buttonAuth.submit">
            提 交
          </a-button>
          <a-button>重 置</a-button>
        </template>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup>
import { ref, toRaw, nextTick } from "vue";
import { Notification } from "@arco-design/web-vue";
import { IconLeft, IconUndo } from "@arco-design/web-vue/es/icon";
import FlowInstApi from "@/api/FlowInstApi";
import ObjectUtil from "@/components/flow/common/ObjectUtil";
import Flow from "@/components/flow/index.vue";
import formatDef from "@/components/flow/common/formatDef.js";
import { cleanUnrequiredWidget } from "@/components/flow/common/FormExp";
import { useFlowStore } from "@/stores/index";
let { flowDefinition } = useFlowStore();

let emits = defineEmits(["ok"]);
const props = defineProps({
  modal: { type: Object, default: () => {} },
});

let showModal = ref(false);
const buttonAuth = ref({}); //按钮权限
// iframe
const iframeRef = ref();
const iframeHeight = ref(0);
const iframeSrc = ref("");

// 查询发起节点按钮权限
const getButtonAuth = (modelId) => {
  FlowInstApi.nodeQuery({
    modelId,
    nodeType: "START_ENV",
  })
    .then((resp) => {
      if (resp.code == 0) {
        const data = resp.data.records;
        buttonAuth.value = data.length && data[0].buttonAuth;
        console.log("buttonAuth", buttonAuth.value);
      }
    })
    .catch(() => {});
};

// tab标签
const activeKey = ref("1");
const tabChange = (key) => {
  if (key == "2") {
    let { nodeConfig, flowWidgets } = flowDefinition;
    cleanUnrequiredWidget(flowWidgets, nodeConfig);
  }
  activeKey.value = key;
};

const setIframeHeight = (height) => {
  iframeHeight.value = height;
};

// 点击提交
const submit = () => {
  // 先获取表单数据
  getFormData();
};

// 通知iframe，且传值
const getFormData = () => {
  // iframe 加载时传递数据给子组件
  if (iframeRef.value) {
    console.log("向子级传值");
    iframeRef.value.contentWindow.postMessage(
      {
        cwd: "get",
      },
      "*"
    );
  }
};
// 接收iframe消息
const handleMessage = (event) => {
  console.log("handleMessage", event);
  if (ObjectUtil.isObject(event.data)) {
    return;
  }
  // 根据上面制定的结构来解析iframe内部发回来的数据
  const data = JSON.parse(event.data);
  const { cwd, formData, height } = data;
  console.log(data);
  if (cwd == "sendData") {
    startFlow(formData);
  }
  if (cwd == "sendHeight") {
    setIframeHeight(height);
  }
};

// 收到表单数据提交发起流程
const startFlow = (formData) => {
  console.log("form data", formData);
  if (!formData.data) {
    Notification.warning(`未获取表单数据`);
    return;
  }
  const { key, id, name } = formModel.value;
  FlowInstApi.flowStart({
    operateType: "START",
    modelId: id,
    modelKey: key,
    formData,
  })
    .then((resp) => {
      launching.value = false;
      if (resp.code == 0) {
        Notification.success(`流程${name}已发起`);
        back();
      }
    })
    .catch(() => {
      launching.value = false;
    });
};

const onSaveModal = () => {};
const show = () => {
  showModal.value = true;

  const { formId, json, id } = props.modal;
  getButtonAuth(id);
  console.log("11", formId, id);
  iframeSrc.value = "";
  nextTick(() => {
    iframeSrc.value = `http://203.33.215.198:9081/#/builder?formId=${formId}`;
    formatDef.formatFlowJson(props.modal);
  });

  window.addEventListener("message", handleMessage);
};
const close = () => {
  showModal.value = false;
  window.removeEventListener("message", handleMessage);
};

defineExpose({ show, close });
</script>
